package com.backend.serializer;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.List;

public class CustomBeanSerializerModifier extends BeanSerializerModifier {
  private final JsonSerializer<Object> nullStringJsonSerializer = new NullStringJsonSerializer();

  @Override
  public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
                                                   List<BeanPropertyWriter> beanProperties) {
    // 循环所有的beanPropertyWriter
    for (BeanPropertyWriter writer : beanProperties) {
      // 判断字段的类型，如果是string boolean则注册nullSerializer
      if (writer.getPropertyType().equals(String.class)) {
        //给writer注册一个自己的nullSerializer
        writer.assignNullSerializer(nullStringJsonSerializer);
      }
    }
    return beanProperties;
  }

}

